-- 發起忘记密码申请

local httparg    = require("shared.api.httparg")
local response   = require("shared.api.response")
local config     = require("config")
local tag        = httparg.tag()
local assertion  = httparg.assertion
local def        = require "shared.api.def"
local httpclient = require "shared.http.client"

local cjson      = require "cjson.safe"
cjson.encode_max_depth(32)
cjson.decode_max_depth(32)


local ARGS = {
  tag.body('json', 'required'),

  password = tag.json.password  ('string','required'),
  token    = tag.json.token     ('string','required'),
}

local RESULT   = {}
do
  local GAAS_SHARED_REDIS  = config.GAAS_SHARED_REDIS
  local redis              = require("shared.api.redis-adapter").new(GAAS_SHARED_REDIS)
  local key                = ARGS.token

  local res, err           = redis:get(key)
  if not res then
      ngx.say("failed to get token: ", err)
      return
  end

  if res == ngx.null then
      response.failure(def.ERROR_CODE.INVALID_ARGUMENT, 'INVALID_ARGUMENT')
      return
  end

  --截取字符串方法
  local function getStr( originStr, strchar, bafter)
      local ts = string.reverse(originStr)
      local param1, param2 = string.find(ts, strchar)  -- 这里以"/"为例
      local m  = string.len(originStr) - param2 + 1
      local result
      if (bafter == true) then
          result = string.sub(originStr, m+1, string.len(originStr))
      else
          result = string.sub(originStr, 1, m-1)
      end
      return result
  end


  --datagate 更新用户密码   username:account
  local location    = config.ENV.DATAGATE_SERVICE .. "/account/profile"
  local headers     = ngx.req.get_headers()
  local query       = nil
  local method      = "UPDATE"
  local bodyMap     = {}
  bodyMap.username  = getStr(tostring(res),":",false)--截取字符串左侧
  bodyMap.account   = getStr(tostring(res),":",true)--截取：字符串右侧

  do

      headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end


  --移除方法设定
  local rmvLowKey="x-http-method-override"
  --移除gzip设定
  local rmvKey2="accept-encoding"
  for k,v in pairs(headers) do
      local low=string.lower(k)
      if low==rmvLowKey  or low==rmvKey2   then
          headers[k]=nil
      end
  end

  bodyMap.content={
      password=ARGS.password
  }
  local requestData = cjson.encode(bodyMap)
  local resp, err   = httpclient.new()
                              :uri(location)
                              :headers(headers)
                              :query(query)
                              :body(requestData)
                              :send(method, 2000, nil)
  if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
  end
  ngx.log(ngx.ERR, resp.body)

end


response.success(RESULT)
